//
//  HFComposeViewController.swift
//  sinaMicroBlog
//
//  Created by mac on 15/11/20.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class HFComposeViewController: UIViewController {

    //待抽象
    @objc private func selectorPicture() {
        selectorVC.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(224 + 80 + 40)
        }
    }
    @objc private func selectorEmoticon() {
        emoticonVC.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(224 + 80 + 40)
        }
        //更改输入键盘
        textView.inputView = emoticonVC.keyBoardView
    }
    
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func send() {
        
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        guard let token = HFUserAccountViewModel().token else {
            SVProgressHUD.showErrorWithStatus("请登录")
            return
        }
        if selectorVC.imageList.count >= 1 {
            let imageData = UIImagePNGRepresentation(selectorVC.imageList[0])
            let parmaters = ["access_token": token, "status": textView.text]
            HFNetWorkTools.sharedTools.uploadImage(urlString, parmaters: parmaters, imageData: imageData!, finished: { (result, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus(AppError)
                    return
                }
                        SVProgressHUD.showSuccessWithStatus("微博发布成功")
                    self.dismissViewControllerAnimated(true, completion: nil)
            })
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        
        setupUI()
    }
    
    private func setupUI() {
        setNavBar()
        setupTextView()
        setupToolBar()
        setSelectorView()
        registerNotification()
    }
    
    private func setSelectorView() {
        //添加子视图控制器
        addChildViewController(selectorVC)
        addChildViewController(emoticonVC)
        //添加视图
        view.addSubview(selectorVC.view)
        view.addSubview(emoticonVC.view)
        
        //调整视图层次结构
        view.bringSubviewToFront(toolBar)
        selectorVC.view.snp_makeConstraints { (make) -> Void in
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(0)
        }
        emoticonVC.view.snp_makeConstraints { (make) -> Void in
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(0)
        }
    }

    private func registerNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    @objc private func keyBoardWillChange(notification: NSNotification) {
        
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let rect = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()

        //更改约束
        let offset = -screenH + rect.origin.y
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offset)
        }
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
    //懒加载
    private lazy var textView: UITextView = {
        let textView = UITextView()
        textView.font = UIFont.systemFontOfSize(18)
        textView.textColor = UIColor.darkGrayColor()
        textView.delegate = self
        
        textView.keyboardDismissMode = .OnDrag
        textView.alwaysBounceVertical = true
        
        return textView
    }()
    private lazy var placeHolderLabel: UILabel = UILabel(title: "分享新鲜事...", size: 18, color: UIColor.lightGrayColor())
    private lazy var toolBar: UIToolbar = UIToolbar()
    private lazy var selectorVC: HFPictureSelectorViewController = HFPictureSelectorViewController()
    private lazy var emoticonVC: HFEmoticonViewController = HFEmoticonViewController()
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

extension HFComposeViewController: UITextViewDelegate {
    func textViewDidChangeSelection(textView: UITextView) {
        placeHolderLabel.hidden = textView.hasText()
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}

extension HFComposeViewController {
    
    private func setupToolBar(){
        view.addSubview(toolBar)
        //设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(40)
        }
        var items = [UIBarButtonItem]()
        let itemSettings = [["imageName": "compose_toolbar_picture","action": "selectorPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","action": "selectorEmoticon"],
            ["imageName": "compose_add_background"]]
        
        for dict in itemSettings {
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, action: dict["action"])
            items.append(item)
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        items.removeLast()
        toolBar.items = items
        
    }

    
    private func setupTextView() {
        view.addSubview(textView)
//        textView.backgroundColor = UIColor.randomColor()
        //设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(view.bounds.height / 3)
        }
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
        
    }
    //设置导航条
    private func setNavBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "send")
        self.navigationItem.rightBarButtonItem?.enabled = false
        
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        navigationItem.titleView = titleView
        
        let titleLabel = UILabel(title: "发微博", size: 17, color: UIColor.darkGrayColor())
        let nameLabel = UILabel(title: HFUserAccountViewModel().userName ?? "", size: 14, color: UIColor.lightGrayColor())
        //添加子视图
        titleView.addSubview(titleLabel)
        titleLabel.addSubview(nameLabel)
        
        //设置约束
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
    }

}
